package no.ntnu.fp.messages.impl;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import no.ntnu.fp.utils.XmlParser;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;

/**
 * Sent by client to server in order to log in.
 * @author benjamin
 *
 */
public class LoginMessage implements Message {
	private final String username, password;

	public LoginMessage() {
		this(null, null);
	}
	
	public LoginMessage(String username, String password) {
		this.username = username;
		this.password = password;
	}
	
	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	@Override
	public MessageCode getMessageCode() {
		return MessageCode.LOGIN_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document dom = XmlParser.parseXmlString(xml);
		return new LoginMessage(XmlParser.getTextValue(dom.getDocumentElement(), "username"),
				XmlParser.getTextValue(dom.getDocumentElement(), "password"));
	}

	@Override
	public String toString() {
		Document dom = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		Element rootElement = dom.createElement("message");
		rootElement.appendChild(XmlParser.createElementWithValue(dom, "username", this.username));
		rootElement.appendChild(XmlParser.createElementWithValue(dom, "password", this.password));
		
		return this.getMessageCode().toString() + "" + XmlParser.convertXmlToString(rootElement);
	}
}
